from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.core.dependencies import get_db
from app.schemas.item import ItemCreate, ItemResponse, ItemUpdate
from app.schemas.response import success, success_list, error
from app.models.user import User
from app.services.impl.ItemServiceImpl import item_crud
from typing import List


router = APIRouter()


# 获取所有物品
@router.get("/")
async def read_items(db: Session = Depends(get_db)):
    items = item_crud.get_all(db)
    return success_list(items, len(items))


# 创建物品
@router.post("/")
async def create_item(item_in: ItemCreate, db: Session = Depends(get_db)):
    # 检查用户是否存在
    user = db.query(User).filter(User.id == item_in.owner_id).first()
    if not user:
        return error("User not found", 400)
        
    created_item = item_crud.create(db, obj_in=item_in)
    return success(created_item)


# 获取特定物品
@router.get("/{id}")
async def read_item(id: int, db: Session = Depends(get_db)):
    item = item_crud.get(db, id=id)
    if item is None:
        return error("Item not found", 404)
    return success(item)


# 更新物品
@router.put("/{id}")
async def update_item(id: int, item_in: ItemUpdate, db: Session = Depends(get_db)):
    item = item_crud.get(db, id=id)
    if item is None:
        return error("Item not found", 404)
    
    # 检查用户是否存在
    user = db.query(User).filter(User.id == item_in.owner_id).first()
    if not user:
        return error("User not found", 400)
    
    # 更新物品信息
    updated_item = item_crud.update(db, item, item_in)
    return success(updated_item)


# 删除物品
@router.delete("/{id}")
async def delete_item(id: int, db: Session = Depends(get_db)):
    item = item_crud.get(db, id=id)
    if item is None:
        return error("Item not found", 404)
        
    deleted_item = item_crud.delete(db, item)
    return success(deleted_item)